package net.tngou.iask.imsdk;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.FileBasedConfiguration;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;

import net.tngou.iask.http.HttpSession;
import net.tngou.iask.http.SessionContext;



/**
 * 手机验证码
 * @author tngou@tngou.net
 *
 */
public class SMUtil {
	private static String RSET="密码重置验证码{1}，请于20分钟内填写。如非本人操作，请忽略本短信。";
	private static String REG="注册验证码{1}，请于20分钟内填写。如非本人操作，请忽略本短信。 ";
	private static String BIND="{1}为您的验证码，请于20分钟内填写。如非本人操作，请忽略本短信。";
	public static void main(String[] args) {
		sendRegMsg("13880334484");
	}
	
	/**
	 * 
	 * @param nationCode 国际编码
	 * @param phoneNumber 电话号码
	 * @param content 发送内容随机数
	 * @return
	 */
	public static boolean sendMsg(String nationCode, String phoneNumber, String tpl,String code) {
		String content=StringUtils.replace(tpl, "{1}", code);
		boolean b = SmsSender.sendMsg(nationCode, phoneNumber, content);
		if(b)
		{
			HttpSession session = new SessionContext();
			 session.setAttribute(nationCode+phoneNumber, code);
		}
		return b;
	}
	public static boolean sendMsg( String phoneNumber,String tpl, String code) {		
		return sendMsg("86", phoneNumber,tpl, code);
	}
	
	public static boolean sendRegMsg( String phoneNumber) {	
		int content=(int)(Math.random()*(9999-1000+1))+1000;//1000-9999的随机数
		return sendMsg( phoneNumber, REG,content+"");
	}
	public static boolean sendBindMsg( String phoneNumber) {	
		int content=(int)(Math.random()*(9999-1000+1))+1000;//1000-9999的随机数
		return sendMsg( phoneNumber, BIND,content+"");
	}
	
	public static boolean sendRsetMsg( String phoneNumber) {	
		int content=(int)(Math.random()*(9999-1000+1))+1000;//1000-9999的随机数
		return sendMsg( phoneNumber, RSET,content+"");
	}
	
	/**
	 * 校对验证码
	 * @param nationCode 国际编码
	 * @param phoneNumber 电话号码
	 * @param content  验证码
	 * @return
	 */
	public static boolean checkCode(String nationCode, String phoneNumber, String content) {		
		HttpSession session = new SessionContext();		
		return content.equals(session.getAttribute(nationCode+phoneNumber));
	}
	public static boolean checkCode(String phoneNumber, String content) {		
		return checkCode("86", phoneNumber, content);
	}
	
}


class SmsSender {
   private static Random random = new Random();
   private static int sdkappid;
   private static String appkey;
    // 请根据我们的说明文档适时调整 url
   private  static String url ;
    
    static
    {
    	 try {
			sdkappid = Config().getInt("smsappid");
			appkey = Config().getString("smsappkey");
			url = Config().getString("smsurl");
		} catch (ConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    }
   
    
    public static boolean sendMsg(String nationCode, String phoneNumber, String content) {
        long rnd = random.nextInt(999999)%(999999-100000+1)+100000;
        String wholeUrl = String.format("%s?sdkappid=%d&random=%d", url, sdkappid, rnd);        
        try {
            URL object = new URL(wholeUrl);
            HttpURLConnection con = (HttpURLConnection) object.openConnection();
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Accept", "application/json");
            con.setRequestMethod("POST");
            JSONObject data = new JSONObject();
            JSONObject tel = new JSONObject();
            tel.put("nationcode", nationCode);
            String phone = phoneNumber;
            tel.put("phone", phone);
            data.put("type", "0");
            data.put("msg", content);
            String sig = stringMD5(appkey.concat(phone));
            data.put("sig", sig);
            data.put("tel", tel);
            OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "utf-8");
            wr.write(data.toString());
            wr.flush();

            // 显示 POST 请求返回的内容
            StringBuilder sb = new StringBuilder();
            int HttpResult = con.getResponseCode();
            if (HttpResult == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                System.out.println("" + sb.toString());
                return true;
            } else {
                System.out.println(con.getResponseMessage());
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static String stringMD5(String input) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        byte[] inputByteArray = input.getBytes();
        messageDigest.update(inputByteArray);
        byte[] resultByteArray = messageDigest.digest();
        return byteArrayToHex(resultByteArray);
    }

    private static String byteArrayToHex(byte[] byteArray) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] resultCharArray = new char[byteArray.length * 2];
        int index = 0;
        for (byte b : byteArray) {
            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b & 0xf];
        }
        return new String(resultCharArray);
    }
    
    /**
	 * 取得配置文件
	 * @return
	 * @throws ConfigurationException 
	 */
	private static Configuration Config() throws ConfigurationException {
		Parameters params = new Parameters();
		FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
		    new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
		    .configure(params.properties()
		        .setFileName("sm.properties"));
	
			Configuration config = builder.getConfiguration();
			return config;
		
	
	}
}
